﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataType;

namespace Utilities
{
    public delegate void NotifyDelegate<T>(T t);
    public delegate void OperationDelegate();

    public class DoOperationASync<T> where T : EventArgs, new()
    {
        
        private T m_Param;
        private EventHandler<T> m_ActionDelegate;
        private OperationDelegate m_Finish;

        private void EndAction(IAsyncResult Ar)
        {
            try{
                OperationDelegate Finish = (OperationDelegate)Ar.AsyncState;
                Finish.EndInvoke(Ar);
            }
            catch(Exception)
            {
            }
            finally
            {
                m_Finish();
            }
        }

        private void DoAction()
        {
            m_ActionDelegate(this, m_Param);
        }

        public void StartAction()
        {
            OperationDelegate Action = this.DoAction;
            Action.BeginInvoke(this.EndAction, Action);
        }

        public DoOperationASync(EventHandler<T> ActionDelegate, T param, OperationDelegate finish)
        {
            this.m_ActionDelegate = ActionDelegate;
            this.m_Param = param;
            this.m_Finish = finish;
        }
    }

    public class DoIterationASync<T> where T : Google.GData.Client.Entry, new()
    {
        //internal delegate void IterationDelegate();
        private NotifyDelegate<T> m_Notify;
        private OperationDelegate m_Finish;
        private EventHandler<FeedWrapper<T>> m_ActionDelegate;

        private void EndAction(IAsyncResult Ar)
        {
            try
            {
                OperationDelegate Finish = (OperationDelegate)Ar.AsyncState;
                Finish.EndInvoke(Ar);
            }
            catch (Exception)
            {
            }
            finally
            {
                m_Finish();
            }
        }

        private void DoAction()
        {
            FeedWrapper<T> Wrapper = new FeedWrapper<T>();
            m_ActionDelegate(this, Wrapper);

            foreach (T type in Wrapper.m_Feed.Entries)
            {
                m_Notify(type);
            }
        }

        public void StartAction()
        {
            OperationDelegate Action = this.DoAction;
            Action.BeginInvoke(this.EndAction, Action);
        }

        public DoIterationASync(EventHandler<FeedWrapper<T>> ActionDelegate, NotifyDelegate<T> Notify, OperationDelegate Finish)
        {
            this.m_ActionDelegate = ActionDelegate;
            this.m_Notify = Notify;
            this.m_Finish = Finish;
        }
    }

}
